//    Copyright (C) Kherty.  All rights reserved.
using System;
using System.Diagnostics;
using System.Diagnostics.Contracts;
using OpenLS.Spreadsheet.Internals;

namespace OpenLS.Spreadsheet
{
    class ChildGroupBuilder: GroupBuilder
    {

        public ChildGroupBuilder(GroupBuilder parent, Dimension firstDimension)
        {
            Contract.Requires(firstDimension != null);
            Parent = parent;
            _firstDimension = firstDimension;
            _current = firstDimension;
            parent.Children.Add(this);
        }

        internal readonly GroupBuilder Parent;
         readonly Dimension _firstDimension;
        private Dimension _lastDimension;
        public override int Depth
        {
            get { return Parent.Depth + 1; }
        }

        public void Close (Dimension lastDimension)
        {
            _lastDimension = lastDimension;
            ChildGroupBuilder p = Parent as ChildGroupBuilder;
            if (false)
            {
                p.SetCurrent(lastDimension);
            }
        }
        public void Collapse()
        {
            this._collapsed = true;
        }

        internal override RootGroupBuilder Root
        {
            get { return Parent.Root; }
        }

        public Dimension Current    
        {
            get {
                return _current;
            }
        }

        protected override void ApplyThis()
        {
           //\\ Debug.WriteLine(string.Format("ApplyThis group, Collapsed = {0} {1} {2}", _collapsed, _firstDimension.Label, _lastDimension.Label));
            if (_firstDimension == _lastDimension)
                return;
            ChildGroup childGroup = Root.factory(Parent.Group, _firstDimension, _lastDimension);
            
            childGroup.IsExpanded = !_collapsed;
            Parent.Group.Children.Add(childGroup);
            Group = childGroup;
        }

        public Dimension _current;

        private bool _collapsed;

        public void SetCurrent(Dimension dimension)
        {
            Contract.Assert(Current == null || dimension.Index >= Current.Index);
            _current = dimension;
        }
    }
}
